﻿using FreeSql;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using XKPlatform.DataModels.DBHelper;

namespace XKPlatform.DataModels.Dao.BaseDao
{
    public static class Db
    {
        // public static System.Collections.Generic.Dictionary<string, IFreeSql> ConnectionPool = new System.Collections.Generic.Dictionary<string, IFreeSql>();
        
        public static IFreeSql freesql { get; } =
               new FreeSql.FreeSqlBuilder()
                 .UseConnectionString(DataType.SqlServer, StaticClass.ConnStr)
                 .UseAutoSyncStructure(false) // 自动同步实体结构
                 .UseNoneCommandParameter(true)
                 .UseMonitorCommand(
                    cmd =>
                    {
                        //Trace.WriteLine(cmd.CommandText);
                        //Console.WriteLine(cmd.CommandText);
                    }, //监听SQL命令对象，在执行前
                    (cmd, traceLog) =>
                    {
                        //Console.WriteLine(traceLog);
                    }) //监听SQL命令对象，在执行后
                .UseLazyLoading(true)
                .Build();

        private static IFreeSql SelectDBType(IFreeSql freesq)
        {
            //var dbtype = enum_dbtype.ToString();
            ////if (!ConnectionPool.ContainsKey(dbtype))
            ////{
            //var freesql = new FreeSql.FreeSqlBuilder()
            //     .UseConnectionString(enum_dbtype, StaticClass.ConnStr)
            //     .UseAutoSyncStructure(false) // 自动同步实体结构
            //     .UseNoneCommandParameter(true)
            //     .UseMonitorCommand(
            //        cmd =>
            //        {
            //            //Trace.WriteLine(cmd.CommandText);
            //            //Console.WriteLine(cmd.CommandText);
            //        }, //监听SQL命令对象，在执行前
            //        (cmd, traceLog) =>
            //        {
            //            //Console.WriteLine(traceLog);
            //        }) //监听SQL命令对象，在执行后
            //    .UseLazyLoading(true)
            //    .Build();

            freesql.Aop.ConfigEntityProperty += Aop_ConfigEntityProperty;

            //SysSubTableConfigModel sysSubTableConfigModel = freesq.Select<SysSubTableConfigModel>().Where(t => t.TableName == "SysOperationLog").ToOne();
             string tableName="";
            //if (sysSubTableConfigModel == null)
            //{
            //    tableName = "SysOperationLog";
            //}

            //tableName = string.IsNullOrEmpty(sysSubTableConfigModel.CurrentSubTableName) ? sysSubTableConfigModel.TableName : sysSubTableConfigModel.CurrentSubTableName;

            //打印执行sql 日志
            freesql.Aop.CurdAfter += ((s, e) =>
            {

                //Console.WriteLine("FullName:" + e.EntityType.FullName);
                //Console.WriteLine("Time: " + e.ElapsedMilliseconds + " ms");
                 Console.WriteLine( DateTime.Now+"sql:" + e.Sql);

                //if (!e.EntityType.FullName.Contains("SysOperationLog") && !e.EntityType.FullName.Contains("SysSubTableConfig") && e.ElapsedMilliseconds > 500)
                //{
                //    SysOperationLog sysOperationLogModel = new SysOperationLog
                //    {
                //        ID = Guid.NewGuid().ToString(),
                //        IPAddress = "",
                //        CreatedBy = "",
                //        CreatedOn = DateTime.Now,
                //        Method = "",
                //        RecordStatus = false,
                //        RequestParams = e.Sql,
                //        RequestPath = e.EntityType.FullName,
                //        UserName = "",
                //        TakeUpTime = e.ElapsedMilliseconds,
                //        LogType = 2
                //    };
                //    freesq.GetGuidRepository<SysOperationLog>(null, astable => tableName).Insert(sysOperationLogModel);
                //}
            });
            return freesql;
            //    ConnectionPool.Add(dbtype, freesql);
            //}
            //return ConnectionPool[dbtype];
        }

        private static void Aop_ConfigEntityProperty(object s, FreeSql.Aop.ConfigEntityPropertyEventArgs e)
        {
            //默认设置主键
            if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any())
            {
                e.ModifyResult.IsPrimary = true;
            }

            //Console.WriteLine("FullName:"+e.EntityType.FullName+" Time: "+e.ElapsedMilliseconds+"ms  sql "+e.Sql)
            ////设置maxlength
            //if (e.Property.PropertyType == typeof(string))
            //{
            //    var strLen = e.Property.GetCustomAttribute<System.ComponentModel.DataAnnotations.MaxLengthAttribute>();
            //    if (strLen != null)
            //    {
            //        e.ModifyResult.DbType = FreeSql.ICodeFirst.GetDbInfo(e.Property.PropertyType)?.dbtype + "(" + strLen.Length + ")";
            //    }
            //}
        }

        public static IFreeSql DB(this DataType t)
        {
            SelectDBType(freesql);
            return freesql;// SelectDBType(t);


        }
    }
}
